<?php
/**
 * Created by PhpStorm.
 * User: eugene
 * Date: 2018/5/24
 * Time: 11:11
 */

namespace App\Http\Controllers;

use App\Exception\UserNotFoundException;
use Illuminate\Routing\Controller as BaseController;
use App\Models\Member;
use App\Repos\MemberRepo;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Support\Facades\Log;

class ApiController extends BaseController
{
    use ValidatesRequests;
    protected $request;
    protected $meta;
    public $user;
    public $card_series_id;
    
    public function __construct()
    {
        $this->request=app('request');
        $this->user = Member::find(config('car.api_config.demo_user_id'));
        //if(!$this->user){
            //$user_token_name = 'user_token';
            //$user_token = $this->request->input($user_token_name);
            //if(!$user_token){
            //    $user_token = Cookie::get($user_token_name);
            //}
            //$this->user = MemberRepo::findUser($user_token);
        //}
        
        if(!$this->user){
            $this->user = Member::find($this->request->input('user_id'));
        }
        if(!$this->user){
            $this->user = Member::find(Cookie::get('user_id'));
        }
    
        throw_unless($this->user,UserNotFoundException::class);
        
    }
    
    
    protected function success($data)
    {
        $url = $this->request->fullUrl();
        $params = $this->request->all();
        $cookies = $_COOKIE;
        $meta = $this->meta;
        if(env('APP_DEBUG'))Log::info('api success:'.json_encode(compact('url','params','cookies','meta','data')));
        
        $data = $data?:[];
        return response()->json([
            'code'=>0,
            'message'=>config('errorcode')[0],
            'meta'=>$this->meta,
            'data'=>$data
        ]);
    }
    
    protected function error($code,$message='')
    {
        if(is_string($code)){
            $message = $code;
            $code = 1;
        }
        if(env('APP_DEBUG'))Log::error('api error:'.json_encode(compact('code','message')));
        return response()->json([
            'code'=>$code,
            'message'=>$message ?: config('errorcode')[(int)$code],
            'meta'=>[],
            'data'=>[]
        ]);
    }
    
    protected function setMeta($meta)
    {
        $this->meta = $meta;
        
        return $this;
    }
    
    protected function setPage($hasMorePages)
    {
        $this->meta = ['next_page'=>(int)$hasMorePages];
        return $this;
    }
}